import 'dart:convert';
import 'package:base_flutter/base_flutter.dart' as b;
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_elder/page/elder_care_selected_page.dart';
import 'package:ls_work/a_yyt/models/care_report_entity.dart';
import 'package:ls_work/a_yyt/models/pending_selected_group_entity.dart';
import 'package:ls_work/a_yyt/models/service_area_entity.dart';
import 'package:ls_work/a_yyt/page/care_search_page.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/mvp/base_page_state.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/provider/base_list_provider.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/a_yyt/widget/care_report_cell.dart';
import 'package:ls_work/a_yyt/presenter/care_report_presenter.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
// import 'package:ls_work/a_elder/elder_router.dart';
// import 'package:ls_work/routers/fluro_navigator.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/event_bus.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/my_refresh_divider_list.dart';
import 'package:ls_work/widgets/state_layout.dart';
import 'package:provider/provider.dart';

import '../../ui/nurse/nurse_record_detail_page.dart';



class HomeCareReportPage extends StatefulWidget {
  final int type; //0默认是首页的照护记录，1为老人照护记录
  final String? elderNameLike;
  final int? customerId;
  final ElderInfo? info;
  HomeCareReportPage({
    Key? key,
    this.type = 0,
    this.elderNameLike,
    this.customerId,
    this.info,
  });
  @override
  HomeCareReportPageState createState() => HomeCareReportPageState();
}

class HomeCareReportPageState
    extends BasePageState<HomeCareReportPage, CareReportPresenter>
    with AutomaticKeepAliveClientMixin {
  BaseListProvider<CareInfo> provider = BaseListProvider<CareInfo>();

  IconData? icon;
  Function()? onTap;
  String _keyword = '';
  int _page = 1;

  List<ServiceAreaInfo> areaList = [];
  List<PendingSelectedGroupEntity>? chipDateList;
  String _starTime = '';
  String _endTime = '';
  DateTime? _startDateTime;
  DateTime? _endDateTime;
  String _serviceAreaIds = '';
  int? _queryTimeType;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    chipDateList = [
      PendingSelectedGroupEntity(isSelected: false, id: 1, name: '今天'),
      PendingSelectedGroupEntity(isSelected: false, id: 2, name: '最近一周'),
      PendingSelectedGroupEntity(isSelected: false, id: 4, name: '最近一月'),
    ];

    icon = widget.type == 0 ? Icons.search : Icons.add;
    onTap = widget.type == 0 ? _search : _add;

    /// 默认为加载中状态
    provider.setStateType(StateType.empty);
    _page = 1;
    if (widget.type == 1 && widget.elderNameLike != null) {
      _keyword = widget.elderNameLike??"";
    }

    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      print(presenter);
      _fectServiceAreaData();
      presenter.fectData(
        true,
        page: _page,
        elderNameLike: _keyword,
        createDateEnd: _endTime,
        createDateStart: _starTime,
        serviceAreaIds: _serviceAreaIds,
      );
    });

    eventBus.on(Constant.eventElderCareAdd, (arg) {
      _onRefresh();
    });

    super.initState();
  }

  @override
  void dispose() {
    // eventBus.off(Constant.eventElderCareAdd);
    super.dispose();
  }

  _search() {
    AppNavigator.push(context, CareSearchPage());
  }

  _add() {
    AppNavigator.push(
      context,
      ElderCareSelectedPage(
        customerId: widget.customerId,
        info: widget.info,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        appBar: AppBar(
          title: Text('照护记录'),
          elevation: 0.5,
          actions: <Widget>[
            TextButton(
              onPressed: onTap,
              child: Icon(
                icon,
                color: Colors.black,
                size: 30,
              ),
            ),
          ],
        ),
        body: ChangeNotifierProvider<BaseListProvider<CareInfo>>(
          create: (_) => provider,
          child:
              Consumer<BaseListProvider<CareInfo>>(builder: (_, provider, __) {
            return Column(
              children: [
                widget.type != 1 ? _topFiltterView() : SizedBox(),
                Expanded(
                  child: DeerSeparatedListView(
                    key: Key('follow_warning_list'),
                    itemCount: provider.list.length,
                    stateType: provider.stateType,
                    onRefresh: _onRefresh,
                    loadMore: _loadMore,
                    hasMore: provider.hasMore,
                    itemBuilder: (_, index) {
                      var info = provider.list[index].bean;
                      return CareReportCell(
                        info: info,
                        deleteClick: (){
                           showApplyDialog(context: context, onSubmit: (){
                             deleteRecord(info?.id);
                           },message: "确定删除该条记录吗？");
                        },
                      ).onTap(() {
                        b.Go().push(NurseRecordDetailPage(detailId: info?.id.toString(),elderInfo: widget.info!,));
                      });
                    },
                    separatorBuilder: (_, int index) => Gaps.line,
                  ),
                ),
              ],
            );
          }),
        ));
  }

  Future<void> deleteRecord(dynamic id) async {
    var map = {
      "id":id
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    try{
      var data = await b.HttpGo.instance.postData(HttpApi.deleteNurseRecord,data: map,options: PostRequest.urlencodedHeader);
      page.closeProgress();
      if("0"==data['code'].toString()){
        showToast("删除成功");
        _onRefresh();
      }else{
        showToast(data['msg']);
      }
    }catch(e){
      page.closeProgress();
      showToast(b.NetErrorUtils.getNetError(e));
    }
  }

  Future _onRefresh() async {
    _page = 1;
    var tempList = [];
    for (var item in areaList) {
      if (item.isSelected) {
        tempList.add(item.id);
      }
    }
    if (tempList.length > 0) {
      _serviceAreaIds = tempList.join(',');
    }
    await presenter.fectData(
      true,
      page: _page,
      elderNameLike: _keyword,
      createDateEnd: _endTime,
      createDateStart: _starTime,
      serviceAreaIds: _serviceAreaIds,
      queryTimeType: _queryTimeType,
    );
    // await presenter.fectData(_keyword, _page, widget.elderNameLike, false);
  }

  Future _loadMore() async {
    _page++;
    await presenter.fectData(
      true,
      page: _page,
      elderNameLike: _keyword,
      createDateEnd: _endTime,
      createDateStart: _starTime,
      serviceAreaIds: _serviceAreaIds,
      queryTimeType: _queryTimeType,
    );
  }

  Widget _topFiltterView() {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.fromLTRB(15, 15, 15, 30),
        color: Colours.bg_color,
        width: ScreenUtil.getScreenW(context),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Gaps.hGap5,
                Container(
                  height: 40,
                  width: (ScreenUtil.getScreenW(context) - 350) / 2,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: InkWell(
                    onTap: () {
                      _showTimePicker(type: 0);
                    },
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            _starTime,
                            textAlign: TextAlign.center,
                            style: TextStyles.textNormal18,
                          ),
                        ),
                        Icon(
                          Icons.arrow_drop_down,
                          color: Colours.text_gray,
                        )
                      ],
                    ),
                  ),
                ),
                Gaps.hGap15,
                Text(
                  '至',
                  style: TextStyles.textDark18,
                ),
                Gaps.hGap15,
                Container(
                  height: 40,
                  width: (ScreenUtil.getScreenW(context) - 350) / 2,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: InkWell(
                    onTap: () {
                      _showTimePicker(type: 1);
                    },
                    child: Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: Text(
                            _endTime,
                            textAlign: TextAlign.center,
                            style: TextStyles.textNormal18,
                          ),
                        ),
                        Icon(
                          Icons.arrow_drop_down,
                          color: Colours.text_gray,
                        )
                      ],
                    ),
                  ),
                ),
                Gaps.hGap15,
                Wrap(
                  spacing: 15,
                  children: (chipDateList??[]).map(
                    (f) {
                      return ChoiceChip(
                        label: Text(f.name??""),
                        selected: f.isSelected==true,
                        selectedColor: Colours.app_main,
                        disabledColor: Colours.bg_color,
                        onSelected: (bool value) {
                          setState(
                            () {
                              for (var item in (chipDateList??<PendingSelectedGroupEntity>[])) {
                                if (item.id == f.id) {
                                  item.isSelected = value;
                                  if (value) {
                                    _queryTimeType = item.id;
                                  } else {
                                    _queryTimeType = null;
                                  }
                                } else {
                                  item.isSelected = false;
                                }
                              }
                              _onRefresh();
                            },
                          );
                        },
                      );
                    },
                  ).toList(),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.only(top: 15, bottom: 8),
              child: Text(
                '区域',
                style: TextStyles.textDark20,
              ),
            ),
            Wrap(
              spacing: 15,
              children: List<Widget>.generate(
                areaList.length,
                (int index) {
                  return ChoiceChip(
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    label: Text('${areaList[index].name ?? ''}'),
                    backgroundColor: Colours.text_gray,
                    selectedColor: Colors.blue[300],
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(3.0),
                    ),
                    onSelected: (bool selected) {
                      setState(() {
                        areaList[index].isSelected = selected;
                        _onRefresh();
                      });
                    },
                    selected: areaList[index].isSelected,
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  CareReportPresenter createPresenter() {
    return CareReportPresenter();
  }

  _fectServiceAreaData() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post('${HttpApi.serviceAreaList}').then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            ServiceAreaEntity model = ServiceAreaEntity.fromJson(map['data']);
            setState(() {
              areaList = model.rows??[];
            });
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///调起时间选择器
  _showTimePicker({int? type}) {
    DatePicker.showDatePicker(
      context,
      minDateTime: DateTime.parse("1900-01-01 00:00"),
      maxDateTime: DateTime.now(),
      initialDateTime: DateTime.now(),
      dateFormat: DateFormats.y_mo_d,
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定'),
      ),
      pickerMode: DateTimePickerMode.date, // show TimePicker
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          print(dateTime);
          if (dateTime == null) {
            return;
          }
          if (type == 0) {
            _startDateTime = dateTime;
            _starTime =
                DateUtil.formatDate(dateTime, format: DateFormats.y_mo_d);
          } else {
            _endDateTime = dateTime;
            _endTime =
                DateUtil.formatDate(dateTime, format: DateFormats.y_mo_d);
          }
          if (_startDateTime != null && _endDateTime != null) {
            if (_endDateTime!.compareTo(_startDateTime!) == -1) {
              Toast.show('结束时间必须大于开始时间');
              setState(() {
                _endDateTime = null;
                _endTime = '';
              });
            } else {
              _onRefresh();
            }
          }
        });
      },
    );
  }
}
